# !/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名：tcpserver.py
import socket
import time
import subprocess
import locale
import codecs


def second_floor_speed_test(bind_width, package_size):
    print("开始测试，测试带宽为：" + str(bind_width) + "MB/s，测量数据的大小为" + str(package_size) + "MB，（单位均为字节）")
    ps = subprocess.Popen(
        '.\iperf3_2\iperf3_2.exe -c 10.112.149.27 -u -b ' + str(bind_width) + 'M -n ' + str(package_size) + 'M',
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        shell=True)
    resultlist = getstdout(ps)
    l = len(resultlist)
    print(resultlist[l - 4])
    speed = str(resultlist[l - 4]).split("  ")[5]
    lost_rate = str(resultlist[l - 4]).split("  ")[7]
    print("当前测试平均速度：" + speed + "；" + "当前测试平均丢包率：" + lost_rate + "；")
    print("本次测量结束...等待下一次测量...")


def getstdout(p):
    mylist = []
    while True:
        data = p.stdout.readline()
        if data == b'':
            if p.poll() is not None:
                break
        else:
            mylist.append(data.decode(codecs.lookup(locale.getpreferredencoding()).name))
    return mylist


MaxBytes = 1024 * 1024

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.settimeout(60)
host = '10.112.149.27'
# host = socket.gethostname()
port = 2333
server.bind((host, port))  # 绑定端口

FLAG = 0

server.listen(1)  # 监听
try:
    client, addr = server.accept()  # 等待客户端连接
    print(addr, " 连接上了")
    while True:
        data = client.recv(MaxBytes)
        if not data:
            print('数据为空，我要退出了')
            break
        localTime = time.asctime(time.localtime(time.time()))
        print(localTime, ' 接收到数据字节数:', len(data))
        print(data.decode())
        recv = data.decode()
        if recv == "Test begin":
            print("Test begin now!")
            client.send(b"Server has received, iperf3 in server has launched")


            # for i in range(1,5):
            #     client.send("start test".encode())
            #     while True:
            #         data = client.recv(MaxBytes)
            #         recv = data.decode()
            #         print(recv)
            #         if recv == "send finished":
            #             break
            while True:
                with open("C:\\Users\\BUPT\\Desktop\\swc010\\这是我最后的波纹\\txt_gen\\sign.txt", "r") as f:  # 打开文件
                    data = f.read()  # 读取文件
                    f.close()
                    if data == 'new':
                        client.send("start test".encode())
                        subprocess.Popen('.\iperf3.exe -s', stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
                        while True:
                            data = client.recv(MaxBytes)
                            recv = data.decode()
                            print(recv)
                            if recv == "send finished":
                                with open("C:\\Users\\BUPT\\Desktop\\swc010\\这是我最后的波纹\\txt_gen\\sign.txt",
                                          "r+") as f:  # 打开文件
                                    f.write("old")  # 读取文件
                                    f.close()

                                    print("Test stop now!")
                                    client.send(b"Test stopped")
                                    subprocess.Popen('taskkill /f /t /im iperf3.exe', stdin=subprocess.PIPE,
                                                     stdout=subprocess.PIPE,
                                                     shell=True)
                                    data1 = 0
                                    with open("C:\\Users\\BUPT\\Desktop\\swc010\\这是我最后的波纹\\txt_gen\\better.txt",
                                              "r") as f:  # 打开文件
                                        data1 = f.read()  # 读取文件
                                        f.close()
                                        print(data1)
                                    bind_width = data1
                                    package_size = 20
                                    print("开始测试，测试带宽为：" + str(bind_width) + "MB/s，测量数据的大小为" + str(
                                        package_size) + "MB，（单位均为字节）")
                                    ps = subprocess.Popen(
                                        '.\iperf3_2\iperf3_2.exe -c 10.112.168.186 -u -b ' + str(
                                            bind_width) + 'M -n ' + str(
                                            package_size) + 'M',
                                        stdin=subprocess.PIPE,
                                        stdout=subprocess.PIPE,
                                        shell=True)
                                    resultlist = getstdout(ps)
                                    l = len(resultlist)
                                    # print(resultlist)
                                    speed = str(resultlist[l - 4]).split("  ")[5]
                                    lost_rate = str(resultlist[l - 4]).split("  ")[7]
                                    print("当前测试平均速度：" + speed + "；" + "当前测试平均丢包率：" + lost_rate + "；")
                                    print("本次测量结束...等待下一次测量...")

                                break


except BaseException as e:
    print("出现异常：")
    print(repr(e))
finally:
    server.close()  # 关闭连接
    print("我已经退出了，后会无期")
    subprocess.Popen('taskkill /f /t /im iperf3.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
